package univ.bme.accounting.dao;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import univ.bme.accounting.domain.User;

@Stateless
public class UserDAOImpl extends GenericDAOImpl<User> implements UserDAO {

    public UserDAOImpl() {
	super(User.class);
    }
    
    public void delete(User user) {
        super.delete(user.getId(), User.class);
    }

    public User findUserByUsername(String username) {
    	try {
			 CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
	         CriteriaQuery<User> criteriaQuery = criteriaBuilder.createQuery(User.class);
	         Root<User> entityRoot = criteriaQuery.from(User.class);
	         criteriaQuery.where(criteriaBuilder.equal(entityRoot.get("username"), username));
	         criteriaQuery.select(entityRoot);
	         User u = em.createQuery(criteriaQuery).getSingleResult();
	         return u;
         } catch (NoResultException nre){
        	return null;
        }

    }
    
    public List<User> findPublicUsers() {
		CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<User> criteriaQuery = criteriaBuilder.createQuery(User.class);
        Root<User> entityRoot = criteriaQuery.from(User.class);
        criteriaQuery.where(criteriaBuilder.equal(entityRoot.get("visible"), User.PUBLIC_DATA));
        criteriaQuery.select(entityRoot);
        List<User> u = em.createQuery(criteriaQuery).getResultList();
        return u;
   }
}